package main

import (
	"net/http"
	"text/template"
)

// 模板 - 模板引擎
func main() {

	// handle
	// http.HandleFunc("/", welcome)

	// 启动前加载模板
	ts := loadTemplate()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fileName := r.URL.Path[1:]
		t := ts.Lookup(fileName)
		if t != nil {
			err := t.Execute(w, nil)
			if err != nil {
				http.Error(w, http.StatusText(http.StatusInternalServerError),
					http.StatusInternalServerError)
				return
			}
		} else {
			http.Error(w, http.StatusText(http.StatusNotFound),
				http.StatusNotFound)
		}
	})

	// 静态资源文件
	http.Handle("/css/", http.FileServer(http.Dir("wwwroot")))
	http.Handle("/img/", http.FileServer(http.Dir("wwwroot")))

	http.ListenAndServe("localhost:8080", nil)
}
func loadTemplate() *template.Template {
	t := template.New("templates")
	template.Must(t.ParseGlob("templates/*.html"))
	return t
}

// processing
func welcome(writer http.ResponseWriter, request *http.Request) {
	// 解析模板
	tmpl, err := template.ParseFiles("index.html")
	if err != nil {
		writer.WriteHeader(http.StatusInternalServerError)
		writer.Write([]byte("template parse failed"))
		//http.Error(writer, http.StatusText(http.StatusInternalServerError),
		//	http.StatusInternalServerError)
		return
	}

	// 执行模板
	tmpl.Execute(writer, "Hello Template")
}
